<?php

/**
 * 扁鸿网站PHP框架
 * @author xiaogua <huangjunjing@bianhong.com>
 * @package account
 * @version 0.0.1
 * @copyright bianhong.com 2010
 */

namespace Account\Action\Oauth\V2\Auth;

use Account\Action\Misc;

class Index  extends \Account\Action\Base{
    const ERROR_INVALID_REQUEST = "invalid_request";
    const ERROR_UNAUTHORIZED_CLIENT = "unauthorized_client";
    const ERROR_ACCESS_DENIED = "access_denied";
    const ERROR_UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
    const ERROR_INVALID_SCOPE = "invalid_scope";
    const ERROR_SERVER_ERROR="server_error";

    const ERROR_MISS_PARAMETERS = 'miss_parameters';
    
    private $_params = array();
    private $_supported_response_type = array(
        'code',
        'token'
    );
    protected $_defined_params = array(
        'response_type' => 'required',
        'client_id' => 'required',
        'redirect_uri' => 'required',
        'scope' => 'optional',
        'state' => 'optional',
    );
    private $_user_id ;

    function __construct() {
        parent::__construct();
        if (!\F3::get('CACHE')) {
            $url = $_SERVER['HTTP_REFERER'];
            \F3::reroute($url . '&error=' . self::ERROR_SERVER_ERROR);
        }
    }

    public function get() {
       
        if (!$this->_validClient()) {
            return;
        }
        echo \Template::serve('authorize/index.html');
    }

    /*
     * 授权，并写入授权表user_allow_client
     */

    public function post() {

        if (!$this->_validClient()) {
            return;
        }
        $clientCode = new \Axon('client_code');
        $clientCode->load('client_id="' . $this->_params['client_id'] . '"');
        $this->_user_id = $_POST['user_id'];
        \DB::sql(
                'INSERT INTO user_allow_client VALUES (:user_id, :app_id)', array(
            ':user_id' => array($this->_user_id, \PDO::PARAM_INT),
            ':app_id' => array($clientCode->app_id, \PDO::PARAM_INT)
                )
        );
        $this->response();
    }

    /*
     * 登录
     */

    public function put() {

        
        if(strpos($_SERVER['HTTP_REFERER'], 'mobile.bianhong.com')){
            $url = 'http://mobile.bianhong.com/?error=true';
        }else{
            $url = 'https://account.bianhong.com/login';
        }
        
        
        $email = strtolower(\F3::get('POST.email'));
        setcookie("loginEmail", $email, time()+3600, '/');
        if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($email)) {
            setcookie("loginError", 'username', time()+3600, '/');
            \F3::reroute($url);
        }

        $password = \F3::get('POST.password');
        if ((strlen($password)< 6) || (strlen($password)> 16) || empty($password)) {
            setcookie("loginError", 'password', time()+3600, '/');
            \F3::reroute($url);
        }
        
        if (!$this->_validClient()) {
            return;
        }

        $user = new \Axon('user');
        $user->load(array('email=:email', array(':email' => $email )));

        if ($user->dry()) {
            setcookie("loginError", 'username', time()+3600, '/');
            \F3::reroute($url);
        }
        
        if ($user->password != md5($password.$user->password_extension)) {
            setcookie("loginError", 'password', time()+3600, '/');
            \F3::reroute($url);
        }
        
        if(!$user->is_enable){
            setcookie("loginError", 'verify', time()+3600, '/');
            \F3::reroute($url);
        }
        
        \Cache::set('nickname', $user->nickname);
        
        $str = 0;
        if ($_POST['persistent']) {
            $str = time() + 3600 * 24*30;
            setcookie("persistent", 1, $str, '/', 'bianhong.com');
        } else {
            setcookie("persistent", null, 0, '/', 'bianhong.com');
        }
        setcookie("email", $user->email, $str, '/', 'bianhong.com');
        setcookie("name", $user->nickname, $str, '/', 'bianhong.com');
        $this->_user_id = $user->id;
        
//        if ($this->hadAuth()) {
//            $client = new \Axon('client');
//            $client->load('auth_client_id="' . $this->_params['client_id'] . '"');
//            \F3::set('client', $client);
//            \F3::set('site', $this->_params['redirect_uri']);
//            \F3::set('email', $user->email);
//            \F3::set('user_id', $user->id);
//            echo \Template::serve('authorize/auth.html');
//            exit;
//        } else {
            $this->response();
 //       }
    }

    private function hadAuth() {
        $clientCode = new \Axon('client_code');
        $clientCode->load('client_id="' . $this->_params['client_id'] . '"');
        $userAllowClient = new \Axon('user_allow_client');
        $userAllowClient->load('user_id="' . $this->_user_id . '" AND app_id="' . $clientCode->app_id . '"');
        return $userAllowClient->dry();
    }

    private function response() {
        if (!$this->_validClient()) {
            return;
        }

        $client = new \Axon('client');
        $client->load('auth_client_id="' . $this->_params['client_id'] . '"');

        $user_dev = new \Axon('user_dev');
        $user_dev->load('user_id="' . $client->user_id . '"');
        $accessCode = Misc::generateCode(18);

        $user = new \Axon('user');
        $user->load('id="' . $this->_user_id . '"');
        $values = array(
            'client_id' => $this->_params['client_id'],
            'client_secret' => $client->auth_client_secret,
            'expires_in' => time(),
            'grant_type' => $this->_params['response_type'],
            'user_id' => $this->_user_id,
            'client_name' => $client->name,
            'client_email' => $user_dev->dev_email,
            'user_name' => $user->email,
            'is_batch' => $user->is_batch
        );

        \Cache::set($accessCode, $values);

        $data = array('code' => $accessCode);
        $url = $this->_params['redirect_uri'] . '?' . http_build_query($data);
        \F3::reroute($url); //生成accessCode附加到redirect_uri
    }

    protected function _validParams($params) {
        $params = array_intersect_key($params, $this->_defined_params);

        foreach ($this->_defined_params as $k => $v) {
            if ($v == 'required' && !isset($params[$k])) {
                return false;
            }
        }
        $this->_params = $params;
        return true;
    }

    protected function _validClient() {
        //缺少必须的参数
        if (!$this->_validParams($_GET)) {
            $this->_htal(self::ERROR_MISS_PARAMETERS);
            return false;
        }

        //不支持的response_type
        if (!in_array($this->_params['response_type'], $this->_supported_response_type)) {
            $this->_htal(self::ERROR_UNSUPPORTED_RESPONSE_TYPE);
            return false;
        }

        //验证client_id是否存在

        $axon = new \Axon('client_code');
        $axon->load('client_id="' . $this->_params['client_id'] . '"');
        if ($axon->dry()) {
            $this->_htal(self::ERROR_ACCESS_DENIED);
            return false;
        }

        //认证redirect_uri
        if ($axon->redirect_uri != urldecode($this->_params['redirect_uri'])) {
            $this->_htal(self::ERROR_UNAUTHORIZED_CLIENT);
            return false;
        }
        return true;
    }

    protected function _htal($error='') {
        if (!\Data::validURL($this->_params['redirect_uri'])) {
            header("HTTP/1.0 400 Bad Request");
            exit;
        }
        \F3::reroute($this->_params['redirect_uri'] . '?error=' . $error);
    }

}
